package com.zjbd.douyangcommoncore.aop;

import com.zjbd.douyangcommoncore.annotation.DouYangAutoTable;
import com.zjbd.douyangcommoncore.utils.MyBatisPlusCodeGenerator;
import com.zjbd.douyangcommondatasource.config.DatasourceConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;


/**
 * 扫描指定路径下带有@TableGenerator注解的实体类
 */
@Slf4j
@Component
public class EntityAnnotationScanner implements ApplicationListener<ContextRefreshedEvent> {

    // 指定实体类包路径
    private static final String SCAN_PACKAGE = "com.zjbd.douyangcommoncore.po";

    @Autowired
    private DatasourceConfig datasourceConfig;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            // 1. 扫描指定包下的所有类
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            CachingMetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
            String packageSearchPath = ResourceUtils.CLASSPATH_URL_PREFIX
                    + ClassUtils.convertClassNameToResourcePath(SCAN_PACKAGE)
                    + "/**/*.class";
            Resource[] resources = resolver.getResources(packageSearchPath);

            // 2. 遍历类，检查@TableGenerator注解
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    String className = metadataReader.getClassMetadata().getClassName();
                    Class<?> entityClass = Class.forName(className);

                    DouYangAutoTable tableGenerator = AnnotationUtils.findAnnotation(entityClass, DouYangAutoTable.class);
                    if (tableGenerator != null) {
                        // 3. 提取注解信息
                        String tableName = tableGenerator.tableName();
                        boolean generateDao = tableGenerator.generateDao();
                        boolean generateService = tableGenerator.generateService();

                        // 4. 调用生成器（根据开关控制）
                        MyBatisPlusCodeGenerator.generate(datasourceConfig.dataSource(), entityClass, tableName, generateDao, generateService);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
